package org.ymh.unix_file_system.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.ymh.unix_file_system.domain.FileSystemError;
import org.ymh.unix_file_system.domain.GlobalVariable;

/**
 * @author lenovo
 * @description: TODO
 * @date 2023/12/15 17:07
 */
@Component
public class BlockOperate {
    @Autowired
    public GlobalVariable globalVariable;
    @Autowired
    public FileSystemError error;

    /**
     * @Description 分配一个盘块，可用-1
     * @Author lenovo
     * @Date 2023/12/15 17:10
     * @Param 接收一个块编号
     * @Return
     * @Exception
     */
    public boolean blockAllocate(int blockIndex) {
        if(!error.isOutIndex(blockIndex, globalVariable.blockBitMap.length,error.BlockIndexOutOfBoundsError))
            if (!globalVariable.blockBitMap[blockIndex]) {
                globalVariable.blockBitMap[blockIndex] = true;
                globalVariable.superBlock.blockCountRest--;
                return true;
            }
        return false;
    }

    /**
     * @Description 回收盘块
     * @Author lenovo
     * @Date 2023/12/15 17:11
     * @Param
     * @Return
     * @Exception
     */
    public boolean blockRecycle(int blockIndex) {
        if(!error.isOutIndex(blockIndex, globalVariable.blockBitMap.length,error.BlockIndexOutOfBoundsError)) {
            if (globalVariable.blockBitMap[blockIndex]) {
                globalVariable.blockBitMap[blockIndex] = false;
                globalVariable.superBlock.blockCountRest++;
                return true;
            }
        }
        return false;
    }
    public boolean blockIsBeAllocate(int blockIndex)
    {
        if(!error.isOutIndex(blockIndex, globalVariable.blockBitMap.length,error.BlockIndexOutOfBoundsError))
        {
            return globalVariable.blockBitMap[blockIndex];
        }
        return false;
    }
}
